const Koa = require('koa');
const app = new Koa();
const router = require('@koa/router')()
const bodyParser = require('koa-bodyparser');
const jwt = require('jsonwebtoken')
const cors = require('koa-cors');
const global = require('./utils/mysql')
const error = require('./middleware/error_handler')

// 登录
router.post('/login', async ctx => {
    let { name, pwd } = ctx.request.body;
    console.log(ctx.request.body);

    let res = await global.query(`select * from user where name = '${name}'`)
    if (res.length == 0) {
        ctx.body = {
            code: -1,
            msg: '用户名不存在'
        }
    }

    let user = await global.query(`select * from user where name = '${name}' and pwd = '${pwd}'`)
    if (user.length > 0) {
        let token = jwt.sign({ id: user[0].id, name: user[0].name }, 'byp', { expiresIn: '1h' })
        ctx.body = {
            code: 1,
            msg: '登录成功',
            token,
            uid: user[0].id
        }
    }
})

// 获取菜单列表
router.get('/getmenu', async ctx => {
    let { uid } = ctx.query;

    let rid = `select rid from user_role where uid = ${uid}`;
    let pid = `select pid from role_power where rid in (${rid})`;
    let res = await global.query(`select * from power where id in (${pid})`)
    ctx.body = {
        code: 1,
        msg: '获取成功',
        data: res
    }
})

// 获取头像
router.get('/getuserinfo', async ctx => {
    let { uid } = ctx.query;

    let res = await global.query(`select * from user where id = ${uid}`)
    ctx.body = {
        code: 0,
        msg: '获取用户头像成功',
        userinfo: res[0]
    }
})

app.use(error())
app.use(cors())
app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(4000, () => {
    console.log("http://localhost:4000 后台服务器启动成功");
});